/*
 * Copyright (c) 2006-2021, Eywen team
 *
 * SPDX-License-Identifier: BSD
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-09-11     Eywen        the first version
 */

#ifndef COMMON_H
#define COMMON_H

#include <stdint.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <rtdbg.h>
#include <stdbool.h>
#include "ringbuff.h"

#define log_p   rt_kprintf


/* 调试显示等级 */
#define DEBUG_DEFAUT_LEVEL      DEBUG_LEVEL_INFO //DEBUG_LEVEL_OFF

/* 显示等级定义，等级值越小的优先级高，默认值小于等级值打印调试信息 */
#define DEBUG_LEVEL_OFF         0
#define DEBUG_LEVEL_FATAL       1
#define DEBUG_LEVEL_ERROR       2
#define DEBUG_LEVEL_WARN        3
#define DEBUG_LEVEL_INFO        4
#define DEBUG_LEVEL_ALL         5

#define debug_p(...)                do{                     \
                                        log_p(__VA_ARGS__); \
                                        log_p("\r\n");      \
                                    }while(0)

#define _debug_level(__LEVEL__, ...) do{                            \
                                        rt_enter_critical();        \
            log_p("[%s: (%s :%d)]\t", #__LEVEL__, __func__, __LINE__);      \
                                        log_p(__VA_ARGS__);       \
                                        log_p("\n");            \
                                        rt_exit_critical();        \
                                    }while(0)

/* 按照调试等级显示 */
#if (DEBUG_DEFAUT_LEVEL >= DEBUG_LEVEL_FATAL)
#define debug_faltal(...)     _debug_level(faltal,__VA_ARGS__)
#else
#define debug_faltal(...)
#endif
#if (DEBUG_DEFAUT_LEVEL >= DEBUG_LEVEL_ERROR)
#define debug_error(...)      _debug_level(error,__VA_ARGS__)
#else
#define debug_error(...)
#endif
#if (DEBUG_DEFAUT_LEVEL >= DEBUG_LEVEL_WARN)
#define debug_warn(...)       _debug_level(warn,__VA_ARGS__)
#else
#define debug_warn(...)
#endif
#if (DEBUG_DEFAUT_LEVEL >= DEBUG_LEVEL_INFO)
#define debug_info(...)       _debug_level(info,__VA_ARGS__)
#else
#define debug_info(...)
#endif


#define USE_ASSERT_NULL true

#define DEBUG_ASSERT(expr, msg, value)  \
    do  {                               \
        if((expr)){                    \
            debug_faltal(msg, value);   \
            while(1);                   \
        }                               \
    }while(0)

#ifndef NULL
#include <stddef.h>
#endif

#if USE_ASSERT_NULL == true
    #define ASSERT_NULL(p)  DEBUG_ASSERT((p == NULL), "pointer "#p" = NULL", p)
#endif

#define MEM_MALLOC  rt_malloc
#define MEM_FREE    rt_free
#define MEM_MEMSET  rt_memset

#ifndef UNUSED
#define UNUSED(x)   ((void) x)
#endif
void delay_ms(uint32_t ms);
void delay_s(uint32_t s);
void delay_us(uint32_t us);
void debug_hex(uint8_t *arr, int len);
#endif // COMMON_H
